package hot;

import java.util.Arrays;

/**
 * @author way
 * @create 2025-03-19 15:20
 */
public class _152_maxProduct {
    public int maxProduct1(int[] nums) {
        if (nums == null || nums.length == 0) return 0;

        int maxVal = Integer.MIN_VALUE;
        int n = nums.length;

        for (int i = 0; i < n; i++) {
            int product = 1;
            for (int j = i; j < n; j++) {
                product *= nums[j];
                maxVal = Math.max(maxVal, product);
                if (product == 0) break; // 遇到0提前终止内层循环
            }
        }
        return maxVal;
    }

    public int maxProduct(int[] nums) {
        int n = nums.length;
        int[] fMax = new int[n];
        int[] fMin = new int[n];
        fMax[0] = fMin[0] = nums[0];
        for (int i = 1; i < n; i++) {
            int x = nums[i];
            fMax[i] = Math.max(Math.max(fMax[i - 1] * x, fMin[i - 1] * x), x);
            fMin[i] = Math.min(Math.min(fMax[i - 1] * x, fMin[i - 1] * x), x);
        }
        int ans = nums[0];
        for (int i = 1; i < n; i++) {
            ans = Math.max(ans, fMax[i]);
        }

        return ans;
    }
}
